#include "temp_humidity.h"

long lastMsg = 0;
char msg[50];
int value = 0;

DHT dht(DHTPIN, DHTTYPE,11);

const char* ssid = "Mi10";
const char* password = "13960379768czy";
const char* mqtt_server = "192.168.20.180";

//设备详情
String deviceId = "2222bbbb"; 
String deviceType = "温湿度检测模块";
String location = "客厅";

String clientId = "8266:" + deviceType + ":" + deviceId;

//温度湿度
float temperature;
float humidity;

int flag = 1;

unsigned long previousMillis = 0;        // will store last temp was read
const long interval = 2000;     

WiFiClient espClient;
PubSubClient client(espClient);
Ticker myTicker;

extern const char* mqtt_server;

//连接mqtt
void reconnect() {
  while (!client.connected()) {

    // Attempt to connect
    
    if (client.connect(clientId.c_str(),"OFFLINE",1,false,deviceId.c_str())) {

      //发送注册消息
      sendRegisterMsg();
      //订阅消息主题 mqtt_topic_001
      subscribeTopic();
    } else {
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
//获取注册信息的Json并转化为String
String getRegisterJsonString()
{
    String registerStr;
    StaticJsonDocument<200> doc;
    doc["deviceId"] = deviceId;
    doc["deviceType"] = deviceType;
    doc["online"] = "1";
    doc["location"] = location;
    serializeJson(doc, registerStr);
    return registerStr;
}
//订阅主题
void subscribeTopic(){
      client.subscribe("mqtt_topic_001");
}
//发送注册消息的msg
void sendRegisterMsg()
{
    String registerStr = getRegisterJsonString();
    client.publish("register_device",registerStr.c_str()) ;
}
//回调函数
void callback(char* topic, byte* payload, unsigned int length) {
  //接收到消息  这边就可以进行不同的主题判断进入不同的分支函数
  String strTopic = String(topic);
  String msgStr = getMsgStringByPayload(payload,length);

  //判断主题 如果是要获取温湿度 那么直接发送回去
}
//根据payload转化消息String
String getMsgStringByPayload(byte* payload,int length)
{
  String msgStr;
  for (int i = 0; i < length; i++) {
    msgStr +=(char)payload[i];
  }
  return msgStr;
}
//连接wifi
void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }

}
//定时任务
void tickerHandle()
{
  
}
//心跳任务 
void tempHumidityHandle(){
  flag = !flag;
}
